package at.jku.novellbedsidedevice;

import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TimePicker;
import at.jku.novellbedsidedevice.service.AccelerometerService;
import at.jku.novellbedsidedevice.service.AlarmService;

public class AlarmUI extends DialogFragment implements OnTimeSetListener {

	Calendar c = Calendar.getInstance();
	int hour;
	int minute;
	TimePickerDialog dialog;

	public AlarmUI() {
		super();
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		hour = c.get(Calendar.HOUR_OF_DAY);
		minute = c.get(Calendar.MINUTE);

		return dialog = new TimePickerDialog(getActivity(), this, hour, minute, false);
	}

	@Override
	public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
		hour = selectedHour;
		minute = selectedMinute;

		// startService
		Calendar date = new GregorianCalendar();

		date.set(GregorianCalendar.MINUTE, selectedMinute);
		date.set(GregorianCalendar.HOUR_OF_DAY, selectedHour);
		date.set(GregorianCalendar.SECOND, 0);
		date.set(GregorianCalendar.MILLISECOND, 0);
		

		
		if(selectedHour < c.get(Calendar.HOUR_OF_DAY) || (selectedHour == c.get(Calendar.HOUR_OF_DAY) && selectedMinute < c.get(Calendar.MINUTE))){
			date.add(Calendar.DATE, 1);
		}

		Log.i("ActivityListUI", date.toString() + "\n");
		
		getActivity().startService(new Intent(getActivity(), AccelerometerService.class));

		Intent alarmIntent = new Intent(getActivity(), AlarmService.class);
		alarmIntent.putExtra("Time", date);
		getActivity().startService(alarmIntent);
		
		getActivity().recreate();

		dismiss();
	}
}
